package com.house365.core.image;

import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.house365.core.touch.ImageViewTouch;

/**
 * @author py
 * @date 2012-6-29
 * @comment
 * 
 * optimize by Rick Ping at 2013-8-29
 * 1.move all image load actions to sub thread
 * 2.use two  arithmetic  to compute image sample size
 */
public class CacheImageUtil {
	public static enum TextImagePosition {
		background, left, top, right, bottom
	};

	public interface ImageOperate {
		public Bitmap operate(Bitmap bitmap);
	}

	private static WeakHashMap<String, WeakReference<Bitmap>> resourceImageCache = new WeakHashMap<String, WeakReference<Bitmap>>();

	/**
	 * imageview 加载图片操作
	 * @param imageView
	 * @param imageUrl
	 * @param resId
	 * @param scaleType
	 * @param mAil
	 */
	public static void setCacheImage(final ImageView imageView,
      String imageUrl, final int resId, int scaleType,
      AsyncImageLoader mAil) {
    imageView.setImageResource(resId);
    imageView.setScaleType(ScaleType.CENTER);
    if (TextUtils.isEmpty(imageUrl)) {
      return;
    } else {
      if (mAil.getApplication().isEnableImg()) {
        mAil.loadDrawable(imageView,imageUrl,
            new ImageViewLoadListener() {
              public void imageLoaded(Bitmap bitmap,
                  String imageUrl) {
                if (bitmap != null && !bitmap.isRecycled()) {
                  imageView.setScaleType(ScaleType.FIT_XY);
                  ImageUtil.showImage(imageView, bitmap,0);
                } else {
                  imageView.setImageResource(resId);
                  imageView.setScaleType(ScaleType.CENTER);
                }
              }
              @Override
              public void imageLoading() {
                imageView.setImageResource(resId);
                imageView.setScaleType(ScaleType.CENTER);
              }
              @Override
              public void imageLoadedFailure() {
                // TODO Auto-generated method stub
                
              }
            },scaleType);
      } else {
        imageView.setImageResource(resId);
        imageView.setScaleType(ScaleType.CENTER);
      }
    }
  }
	/** 按照ImageView宽度等比例缩放图片 */
	public static void setCacheImageCustom(final ImageView imageView,
			String imageUrl, final int resId, final int scaleType,
			final AsyncImageLoader mAil, final ScaleType scale) {
		imageView.setImageResource(resId);
		imageView.setScaleType(ScaleType.CENTER);
		final ImageViewLoadListener secondListener = new ImageViewLoadListener() {
			public void imageLoaded(Bitmap bitmap,
					String imageUrl) {
				if (bitmap != null && !bitmap.isRecycled()) {
					imageView.setScaleType(scale);
					ImageUtil.showImage(imageView, bitmap,0);
				} else {
					imageView.setImageResource(resId);
					imageView.setScaleType(ScaleType.CENTER);
				}
			}
			@Override
			public void imageLoading() {
				imageView.setImageResource(resId);
				imageView.setScaleType(ScaleType.CENTER);
			}
			@Override
			public void imageLoadedFailure() {
				
			}
		};
		
		if (TextUtils.isEmpty(imageUrl)) {
			return;
		} else {
			if (mAil.getApplication().isEnableImg()) {
				mAil.loadDrawable(imageView,imageUrl,
						new ImageViewLoadListener() {
							public void imageLoaded(Bitmap bitmap,
									String imageUrl) {
								if (bitmap != null && !bitmap.isRecycled()) {
									imageView.setScaleType(scale);
									int height = imageView.getWidth() * bitmap.getHeight()/bitmap.getWidth();
									ViewGroup.LayoutParams lp = imageView.getLayoutParams();
									lp.height = height;
									imageView.setLayoutParams(lp);
									mAil.loadDrawable(imageView, imageUrl, secondListener, scaleType);
									ImageUtil.showImage(imageView, bitmap,0);
								} else {
									imageView.setImageResource(resId);
									imageView.setScaleType(ScaleType.CENTER);
								}
							}
							@Override
							public void imageLoading() {
								imageView.setImageResource(resId);
								imageView.setScaleType(ScaleType.CENTER);
							}
							@Override
							public void imageLoadedFailure() {
								
							}
						},scaleType);
			} else {
				imageView.setImageResource(resId);
				imageView.setScaleType(ScaleType.CENTER);
			}
		}
	}
	
	/**
	 * imageview 加载图片操作
	 * @param imageView
	 * @param imageUrl
	 * @param resId
	 * @param scaleType
	 * @param mAil
	 */
	public static void setCacheImage(final ImageView imageView,
			String imageUrl, final int resId, int scaleType,
			AsyncImageLoader mAil, final ScaleType scale) {
		imageView.setImageResource(resId);
		imageView.setScaleType(ScaleType.CENTER);
		if (TextUtils.isEmpty(imageUrl)) {
			return;
		} else {
			if (mAil.getApplication().isEnableImg()) {
				mAil.loadDrawable(imageView,imageUrl,
						new ImageViewLoadListener() {
							public void imageLoaded(Bitmap bitmap,
									String imageUrl) {
								if (bitmap != null && !bitmap.isRecycled()) {
									imageView.setScaleType(scale);
									ImageUtil.showImage(imageView, bitmap,0);
								} else {
									imageView.setImageResource(resId);
									imageView.setScaleType(ScaleType.CENTER);
								}
							}
							@Override
							public void imageLoading() {
								imageView.setImageResource(resId);
								imageView.setScaleType(ScaleType.CENTER);
							}
							@Override
							public void imageLoadedFailure() {
								// TODO Auto-generated method stub
								
							}
						},scaleType);
			} else {
				imageView.setImageResource(resId);
				imageView.setScaleType(ScaleType.CENTER);
			}
		}
	}
		/**
		 * ImageVIew加载图片操作，附带加载成功、或者失败监听事件
		 * liuziqiang overload setCacheImage
		 * @param imageView
		 * @param imageUrl
		 * @param scaleType
		 * @param mAil
		 * @param imgLoadedObj
		 */
		public static void setCacheImage(final ImageView imageView,
				String imageUrl, int scaleType,
				AsyncImageLoader mAil, final ImageLoadedCallback imgLoadedObj) {
			if (TextUtils.isEmpty(imageUrl)) {
				imgLoadedObj.imageLoadedFail();
			} else {
				if (mAil.getApplication().isEnableImg()) {
					int w = imageView.getWidth();
					int h = imageView.getHeight();
					if(w<0){
						w= -1;
					}
					if(h<0){
						h= -1;
					}
					mAil.loadDrawable(imageView,imageUrl,
							new ImageViewLoadListener() {
								public void imageLoaded(Bitmap bitmap,
										String imageUrl) {
									if (bitmap != null && !bitmap.isRecycled()) {
										imageView.setScaleType(ScaleType.FIT_XY);
										ImageUtil.showImage(imageView, bitmap, 0);
										imgLoadedObj.imageLoadedSuccess();
									} else {
										imgLoadedObj.imageLoadedFail();
									}
								}
								@Override
								public void imageLoadedFailure() {
									imgLoadedObj.imageLoadedFail();
									
								}
								@Override
								public void imageLoading() {
									
									
								}
							},scaleType);
				} else {
					imgLoadedObj.imageLoadedFail();
				}
			}
		}

	/**
	 * 设置手势ImageVIew 图片加载事件
	 * @param imageView
	 * @param imageUrl
	 * @param resource
	 * @param resId
	 * @param scaleType
	 * @param mAil
	 */
	public static void setTouchImage(final ImageViewTouch imageView,	
			String imageUrl, final Resources resource, final int resId,
			int scaleType, AsyncImageLoader mAil) {
		if (TextUtils.isEmpty(imageUrl)) {
			imageView.setImageBitmapResetBase(
					getResourceBitMap(resource, resId), true);
		} else {
			if (mAil.getApplication().isEnableImg()) {
				int w = imageView.getWidth();
				int h = imageView.getHeight();
				if(w<0){
					w= -1;
				}
				if(h<0){
					h= -1;
				}
				 mAil.loadDrawable(imageView,imageUrl,
						new ImageViewLoadListener() {
							public void imageLoaded(Bitmap bitmap,
									String imageUrl) {
								if (bitmap != null && !bitmap.isRecycled()) {
									imageView.setImageBitmapResetBase(bitmap,
											true);
								} else {
									imageView.setImageBitmapResetBase(
											getResourceBitMap(resource, resId),
											true);
								}
							}
							@Override
							public void imageLoadedFailure() {
								// TODO Auto-generated method stub
								
							}
							@Override
							public void imageLoading() {
								imageView.setImageBitmapResetBase(
										getResourceBitMap(resource, resId), true);
								
							}
						},scaleType);
			} else {
				imageView.setImageBitmapResetBase(
						getResourceBitMap(resource, resId), true);
			}
		}
	}

	/**
	 * 获取 resouce cache bitmap
	 * @param resource
	 * @param resId
	 * @return
	 */
	public static Bitmap getResourceBitMap(final Resources resource,
			final int resId) {
		Bitmap bitmap = null;
		String key = resId + "";
		if (resourceImageCache.containsKey(key)) {
			bitmap = resourceImageCache.get(key).get();
			if (bitmap != null && !bitmap.isRecycled()) {
				return bitmap;
			} else {
				resourceImageCache.remove(key);
			}
		}
		while (bitmap == null) {
			try {
				bitmap = BitmapFactory.decodeResource(resource, resId);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
				System.gc();
			}
		}
		return bitmap;

	}

	/***
	 * set text view's drawable which from url
	 * @param textView
	 * @param position
	 *            0 Background left 1 top 2 right 3 bottom 4;
	 * @param imageUrl
	 * @param mAil
	 */
	public static void setCacheTextImage(final TextView textView,
			final TextImagePosition position, String imageUrl,
			AsyncImageLoader mAil) {
		if (!TextUtils.isEmpty(imageUrl)) {
			Bitmap  bitmap=mAil.loadImageFromUrl(imageUrl,0,0,AsyncImageLoader.IMAGE_SCALE_TYPE_NONE);
			if (bitmap != null && !bitmap.isRecycled()) {
				Drawable drawable = new BitmapDrawable(bitmap);
				switch (position) {
				case background:
					textView.setBackgroundDrawable(drawable);
					break;
				case top:
					textView.setCompoundDrawablesWithIntrinsicBounds(
							drawable, null, null, null);
					break;
				case left:
					textView.setCompoundDrawablesWithIntrinsicBounds(
							null, drawable, null, null);
					break;
				case right:
					textView.setCompoundDrawablesWithIntrinsicBounds(
							null, null, drawable, null);
					break;
				case bottom:
					textView.setCompoundDrawablesWithIntrinsicBounds(
							null, null, null, drawable);
					break;
				}

			}
		}
	}

	/**
	 * get bitmap from url and with a operation when it get successful.
	 * @param imageView
	 * @param imageUrl
	 * @param imageOperate
	 * @param resource
	 * @param resId
	 * @param scaleType
	 * @param mAil
	 */
	public static void setCacheImageWithImageOper(final ImageView imageView,
			String imageUrl, final ImageOperate imageOperate,
			final Resources resource, final int resId, int scaleType,
			AsyncImageLoader mAil) {
		Bitmap bitmap;
		imageView.setImageResource(resId);
		imageView.setScaleType(ScaleType.CENTER);
		if (TextUtils.isEmpty(imageUrl)) {
			return;
		} else {
			if (mAil.getApplication().isEnableImg()) {
				mAil.loadDrawable(imageView,imageUrl,
						new ImageViewLoadListener() {
							public void imageLoaded(Bitmap bitmap,
									String imageUrl) {
								if (bitmap != null && !bitmap.isRecycled()) {
									bitmap = imageOperate.operate(bitmap);
									if (bitmap != null && !bitmap.isRecycled()) {
										imageView.setScaleType(ScaleType.FIT_XY);
										ImageUtil.showImage(imageView, bitmap,0);
									}

								} else {
									imageView.setImageResource(resId);
									imageView.setScaleType(ScaleType.CENTER);
								}
							}
							@Override
							public void imageLoadedFailure() {
								// TODO Auto-generated method stub
								
							}
							@Override
							public void imageLoading() {
								imageView.setImageResource(resId);
								imageView.setScaleType(ScaleType.CENTER);
								
							}
						},scaleType);
			} else {
				imageView.setImageResource(resId);
				imageView.setScaleType(ScaleType.CENTER);
			}
		}

	}

	/**
	 * set the imageview's bitmap which get from URL,there will no default image when bitmap get failure
	 * @param imageView
	 * @param imageUrl
	 * @param scaleType
	 * @param mAil
	 */
	public static void setCacheImageWithoutDef(final ImageView imageView,
			String imageUrl, int scaleType, AsyncImageLoader mAil) {
		if (TextUtils.isEmpty(imageUrl)) {
			return;
		} else {
			mAil.loadDrawable(imageView,imageUrl,
					new ImageViewLoadListener() {
						public void imageLoaded(Bitmap bitmap, String imageUrl) {
							if (bitmap != null && !bitmap.isRecycled()) {
								imageView.setScaleType(ScaleType.FIT_XY);
								ImageUtil.showImage(imageView, bitmap,0);
							}
						}
						@Override
						public void imageLoadedFailure() {
							// TODO Auto-generated method stub
							
						}
						@Override
						public void imageLoading() {
							// TODO Auto-generated method stub
							
						}
					},scaleType);
		}

	}
	
	/**
	 * imageview 加载图片操作
	 * @param imageView
	 * @param localFile
	 * @param resId
	 * @param scaleType
	 * @param mAil
	 */
	public static void setCacheImageFromLocalFile(final ImageView imageView,
			String localFile, final int resId, int scaleType,
			AsyncImageLoader mAil) {
		imageView.setImageResource(resId);
		imageView.setScaleType(ScaleType.CENTER);
		if (TextUtils.isEmpty(localFile)) {
			return;
		} else {
				mAil.loadDrawableByLocalFile(imageView,localFile,
						new ImageViewLoadListener() {
							public void imageLoaded(Bitmap bitmap,
									String imageUrl) {
								if (bitmap != null && !bitmap.isRecycled()) {
									imageView.setScaleType(ScaleType.FIT_XY);
									ImageUtil.showImage(imageView, bitmap,0);
								} else {
									imageView.setImageResource(resId);
									imageView.setScaleType(ScaleType.CENTER);
								}
							}
							@Override
							public void imageLoading() {
								imageView.setImageResource(resId);
								imageView.setScaleType(ScaleType.CENTER);
							}
							@Override
							public void imageLoadedFailure() {
								// TODO Auto-generated method stub
								
							}
						},scaleType);
		}
	}
	
	
	public static void setCacheImage(final ImageView imageView,
      String imageUrl, final int resId, int scaleType,
      AsyncImageLoader mAil,int screen) {
    imageView.setImageResource(resId);
    imageView.setScaleType(ScaleType.FIT_XY);
    if (TextUtils.isEmpty(imageUrl)) {
      return;
    } else {
      if (mAil.getApplication().isEnableImg()) {
        mAil.loadDrawable(imageView,imageUrl,
            new ImageViewLoadListener() {
              public void imageLoaded(Bitmap bitmap,
                  String imageUrl) {
                if (bitmap != null && !bitmap.isRecycled()) {
                  imageView.setScaleType(ScaleType.FIT_XY);
                  ImageUtil.showImage(imageView, bitmap,0);
                } else {
                  imageView.setImageResource(resId);
                  imageView.setScaleType(ScaleType.FIT_XY);
                }
              }
              @Override
              public void imageLoading() {
                imageView.setImageResource(resId);
                imageView.setScaleType(ScaleType.FIT_XY);
              }
              @Override
              public void imageLoadedFailure() {
                // TODO Auto-generated method stub
                
              }
            },scaleType);
      } else {
        imageView.setImageResource(resId);
        imageView.setScaleType(ScaleType.CENTER);
      }
    }
  }
	
	
}
